<template>
    <rui-page :defines="defines">
        <rui-query :label-width="300"
                   ref="searchForm"
                   :query="queryData"
                   :query-rows="searchFormOptions"
        />
        <Row>
            <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert>
        </Row>
        <rui-table
            :defineId="'defineTable'"
            :fixedLeft="['action']"
            :showIndex="false"
            :select="true"
            :columns="showColumns"
            :slots="[{key:'action',slot:'action'},{key:'ruleStatus',slot:'ruleStatus'}]"
            @loadDatas="queryData"
            @on-selection-change="changeSelect"
            ref-query="searchForm"
            ref="showTable"
        >
            <template slot="toolBar">
                <Button @click="add" icon="md-add" type="primary">新增</Button>
                <Button @click="effective" type="primary">有效</Button>
                <Button @click="invalid" type="primary">无效</Button>
            </template>
            <template slot="action" slot-scope="{ row, index }">
                <div>
                    <Button @click="edit(row)" size="small" v-if="row.ruleStatus=='0'" type="primary">编辑</Button>
                    <Button type="error" size="small" v-if="row.ruleStatus=='0'" @click="remove(row)">删除</Button>
                    <Button @click="ruleConfig(row)" v-if="row.ruleStatus=='0'" size="small" type="warning">规则配置</Button>
                </div>
            </template>

            <template slot-scope="{ row, index }" slot="ruleStatus">
                <div>
                    <tag v-if="row.ruleStatus=='1'" color="success" size="default">有效</tag>
                    <tag v-if="row.ruleStatus=='0'" color="error" size="default">无效</tag>
                </div>
            </template>

        </rui-table>

        <Modal
            v-model="isShowRule"
            :title="ruleTitle"
            :width="800"
            :closable="false"
            :mask-closable="false"
            @on-ok="saveRule">
            <rui-form  :form-options="ruleFormOptions" :label-width="120" :read-only="false" ref="ruleForm"/>
            <div slot="footer">
                <Button size="small" @click="isShowRule = false">取消</Button>
                <Button type="primary" size="small" @click="saveRule">保存</Button>
            </div>
        </Modal>

        <Modal
            v-model="isShowRuleConfig"
            :title="ruleConfigTitle"
            :width="1000"
            :closable="false"
            :mask-closable="false">
            <rule-tree v-if="dataLoad" :rule-data="ruleData" :ruleAtoms="ruleAtoms" :ruleName="ruleName" :ruleGroup="ruleGroup" :businessScenario="businessScenario" @saved="returnRuleId" :rule-id="ruleId"/>
            <div slot="footer">
                <Button size="small" @click="isShowRuleConfig = false,dataLoad = false">取消</Button>
            </div>
        </Modal>

    </rui-page>
</template>
<script>
    import tableDefine from "../defines/product-rule-info-define";
    import ruiRules from '_c/rui-auto/rui-rules/index';
    import {loadRuleDataById} from '_p/basic/api/rule/rule';
    import {queryAtomsByBizType} from "@/projects/basic/api/rule/ruleAtom";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        getRuleInfoListForce,
        delById,
        addRule,
        editRule,
        effective,
        invalid,
    } from "@/projects/afs-core-business/api/afs-product/product-rule/product-rule-info";

    import {saveRuleOut} from '_p/basic/api/rule/rule';
    import {getUri} from "@/libs/tools";

    export default {
        components: {
            ruleTree: ruiRules
        },
        props: {},
        data() {
            return {
                dataLoad:false,
                isShow: true,
                isShowRule: false,//规则输出信息页面展示
                ruleTitle: null,//规则输出信息页面主题
                isShowRuleConfig: false,//规则配置页面展示
                ruleConfigTitle: null,//规则配置页面主题
                modalType: 0,
                fitScope: '007',
                showColumns: [
                    'action', 'ruleName',"outputInfo","ruleStatus","ruleExpress"
                ],
                searchFormOptions: [
                    {defineId: "defineTable", span: 6, fields: ["ruleName","ruleStatus"]},
                ],
                ruleFormOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'defineTable', span: 24, fields: ['ruleName']},
                            {defineId: 'defineTable', span: 24, fields: ["outputInfo"]},
                        ]
                    }
                ],
                ruleAtoms: [],
                ruleTree: [],
                ruleName: '风控准入配置',
                ruleGroup: 'riskControl',
                businessScenario: 'businessScenario',
                ruleId : null,
                ruleStatus : '0',
                ruleData:[],
                row:{},
                selectList: [],
                selectCount: 0,
            };
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineTable",
                        fields: tableDefine
                    }
                ];
            }
        },
        methods: {
            getSourceList(queryData) {
                console.info("queryData"+queryData);
                queryData["condition"]["fitScope"] = this.fitScope;
                console.info("queryData，condition:"+JSON.stringify(queryData["condition"]));
                getRuleInfoListForce(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.showTable.updateTableData(records, total);
                        this.clearSelectAll();
                    }
                });
                queryAtomsByBizType(this.fitScope,'product').then(res => {
                    if (res.code === "0000") {
                        this.ruleAtoms = res.data;
                    }
                });
            },
            queryData(queryData) {
                this.getSourceList(queryData);
            },
            refresh() {
                this.$refs['showTable'].reloadData();
                this.clearSelectAll();
            },
            clearSelectAll(){
                this.$refs.showTable.getTable().selectAll(false);
            },
            effective() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要设置有效的数据");
                    return;
                }
                if(this.check("effective")){return;}
                this.$Modal.confirm({
                    title: "确认设置有效吗",
                    content: "您确认要设置有效所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach(function (e) {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        effective({ids: ids}).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("设置成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            invalid() {
                if (this.selectCount <= 0) {
                    this.$Message.warning("您还未选择要设置无效的数据");
                    return;
                }
                if(this.check("invalid")){return;}
                this.$Modal.confirm({
                    title: "确认设置无效吗",
                    content: "您确认要设置无效所选的 " + this.selectCount + " 条数据?",
                    onOk: () => {
                        let ids = [];
                        this.selectList.forEach((e) => {
                            ids += e.id + ",";
                        });
                        ids = ids.substring(0, ids.length - 1);
                        invalid({ids: ids}).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("设置成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            check(type){
                console.info(type);
                let invalidNum = 0;
                let effectiveNum = 0;
                this.selectList.forEach((e) => {
                    if(e.ruleStatus==0){//无效
                        invalidNum++;
                    }else if(e.ruleStatus==1){//有效
                        effectiveNum++;
                    }
                });
                console.info("无效数量"+invalidNum);
                console.info("有效数量"+effectiveNum);
                var checkResult = false;
                if("invalid"==type&&invalidNum>0){
                    this.$Message.warning("不可设置无效数据为无效！");
                    checkResult = true;
                }
                if("effective"==type&&effectiveNum>0){
                    this.$Message.warning("不可设置有效数据为有效！");
                    checkResult = true;
                }
                return checkResult;
            },
            changeSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            add() {
                this.ruleTitle = "新增规则";
                this.isShowRule = true;
                this.modalType = 0;
                this.$refs.ruleForm.setAllFieldRequired(true);
                this.$nextTick(() => {
                    this.$refs.ruleForm.resetFrom();

                })
            },
            edit(row) {
                this.$refs.ruleForm.resetFrom();
                this.ruleTitle = "编辑规则";
                this.isShowRule = true;
                this.modalType = 1;
                this.$refs.ruleForm.updateFormData(deepClone(row));
                this.$refs.ruleForm.setAllFieldRequired(true);
            },
            ruleConfig(row) {
                this.row = row;
                this.ruleId = row.ruleId;
                this.ruleName=row.ruleName;
                this.businessScenario = row.id;
                this.ruleConfigTitle = "编辑规则";
                if(row.ruleId!=null){
                    loadRuleDataById(this.ruleId).then(res => {
                        if(res.code='0000'){
                            if(res.data.length>0) {
                                this.ruleData=res.data;
                                this.isShowRuleConfig = true;
                                this.dataLoad = true;
                            }
                        }
                    });
                }else{
                    this.ruleData = [];
                    this.isShowRuleConfig = true;
                    this.dataLoad = true;
                }
            },
            remove(v) {
                this.$Modal.confirm({
                    title: "确认删除吗",
                    content: "您确认要删除这条规则?",
                    onOk: () => {
                        delById(v.id).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("操作成功");
                                this.refresh();
                            }
                        });
                    }
                });
            },
            saveRule() {
                this.$refs.ruleForm.getForm().validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            var param = this.$refs.ruleForm.getFormData();
                            param.fitScope = this.fitScope;
                            param.ruleStatus = this.ruleStatus;
                            addRule(param)
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.refresh();
                                        this.isShowRule = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                        } else {
                            // 编辑
                            let param = this.$refs.ruleForm.getFormData();
                            editRule(param)
                                .then(res => {
                                    if (res.code === "0000") {
                                        this.$Message.success("操作成功");
                                        this.refresh();
                                        this.isShowRule = false;
                                    }
                                })
                                .catch(() => {
                                    this.refresh();
                                });
                            if(param.ruleId!=null){
                                this.saveRuleOut(param.ruleId,param.outputInfo);
                            }
                        }
                    }
                });
            },
            returnRuleId(ruleId,expressValue){
                this.ruleId = ruleId;
                console.log(ruleId);
                this.dataLoad = false;
                this.isShowRuleConfig = false;
                // 编辑
                this.row.ruleId = ruleId;
                this.row.ruleExpress = expressValue;
                this.row.activeStatus = "0";
                editRule(this.row)
                    .then(res => {
                        if (res.code === "0000") {
                            this.refresh();
                        }
                    })
                    .catch(() => {
                        this.refresh();
                    });
                this.saveRuleOut(ruleId,this.row.outputInfo);
            },
            saveRuleOut(ruleId,outputInfo){
                let rule = {
                    "id":ruleId,
                    "ruleOut":outputInfo
                };
                saveRuleOut(rule,getUri('rule')).then(res => {
                    if (res.code === "0000") {
                        this.refresh();
                    }
                }).catch(() => {
                    this.$Message.error("规则输出保存失败！");
                });
            },
        },
        mounted() {
            this.refresh();
        }
    };
</script>
